/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
/**
 *
 */
package com.eelpo.cmmp.uac.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.eelpo.cmmp.core.exception.ServiceException;
import com.eelpo.cmmp.uac.dao.IEnterpriseManageDao;
import com.eelpo.cmmp.uac.dao.IEnterpriseRelationManageDao;
import com.eelpo.cmmp.uac.dao.IUserManageDao;
import com.eelpo.cmmp.uac.dao.entity.TEnterprise;
import com.eelpo.cmmp.uac.dao.entity.TEnterpriseRelation;
import com.eelpo.cmmp.uac.dao.entity.TUser;
import com.eelpo.cmmp.uac.dao.vo.Enterprise;
import com.eelpo.cmmp.uac.dao.vo.enumed.Status;
import com.eelpo.cmmp.uac.services.IEnterpriseManageService;
import com.eelpo.common.util.BlankUtils;

/**
 * <pre>
 * 
 * 
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
@Service
public class EnterpriseManageService implements IEnterpriseManageService {

	@Resource
	protected IUserManageDao userManageDao;

	@Resource
	protected IEnterpriseManageDao enterpriseManageDao;

	@Resource
	protected IEnterpriseRelationManageDao enterpriseRelationManageDao;

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#getEnterpriseById(java.lang.String)
	 */
	@Override
	public Enterprise getEnterpriseById(String id) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#getEnterpriseByName(java.lang.String)
	 */
	@Override
	public Enterprise getEnterpriseByName(String name) throws ServiceException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#checkExist(java.lang.String)
	 */
	@Override
	public boolean checkExist(String name) throws ServiceException {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#addEnterprise(com.eelpo.cmmp.uac.dao.vo.Enterprise)
	 */
	@Override
	public String addEnterprise(Enterprise enterprise) throws ServiceException {

		// 检查企业是否存在
		if (enterpriseManageDao.checkExist(enterprise.getName())) {
			throw new ServiceException("企业[" + enterprise.getName() + "]已经存在！");
		}

		TEnterprise tenterprise = vo2po(enterprise);

		// 如果不是根实体，设置实体与所有上级关系
		if (!BlankUtils.isBlank(enterprise.getParent())) {
			List<TEnterpriseRelation> relations = enterpriseRelationManageDao.getParentRelation(enterprise.getParent().getId());
			for (TEnterpriseRelation relation : relations) {
				tenterprise.getParentRelation().add(new TEnterpriseRelation(relation.getParentEnterprise(), tenterprise, relation.getDepth() + 1));
			}
		}

		// 设置自己和自己的关系
		tenterprise.getParentRelation().add(new TEnterpriseRelation(tenterprise, tenterprise, 0));

		return enterpriseManageDao.addEnterprise(tenterprise);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#updateEnterprise(com.eelpo.cmmp.uac.dao.vo.Enterprise)
	 */
	@Override
	public void updateEnterprise(Enterprise enterprise) throws ServiceException {
		// TODO Auto-generated method stub

	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#deleteEnterprise(com.eelpo.cmmp.uac.dao.vo.Enterprise)
	 */
	@Override
	public void deleteEnterprise(Enterprise enterprise) throws ServiceException {
		// TODO Auto-generated method stub

	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IEnterpriseManageService#getMenuEnterprise(java.lang.String)
	 */
	@Override
	public DefaultTreeModel getEnterprises(String userId) throws ServiceException {

		TUser user = userManageDao.getUserById(userId);

		if (BlankUtils.isBlank(user)) {
			throw new ServiceException("用户不存在！");
		}

		List<TEnterprise> enterprises = new ArrayList<TEnterprise>();

		if (user.getSuperManager()) {
			enterprises = enterpriseManageDao.getEnterprises();
		} else {
			enterprises = enterpriseManageDao.getEnterprises(userId);
		}

		return generateTreeModel(enterprises);
	}

	/**
	 * 生成树结构
	 * 
	 * @param entities
	 *            实体集合
	 * @return 返回树模型
	 */
	private DefaultTreeModel generateTreeModel(List<TEnterprise> entities) {
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
		Map<TEnterprise, DefaultMutableTreeNode> nodeMap = new HashMap<TEnterprise, DefaultMutableTreeNode>();
		for (TEnterprise e : entities) {
			if (entities.contains(e.getParent())) {
				if (nodeMap.containsKey(e.getParent())) {
					if (nodeMap.containsKey(e)) {
						nodeMap.get(e.getParent()).add(nodeMap.get(e));
					} else {
						DefaultMutableTreeNode node = new DefaultMutableTreeNode(po2vo(e));
						nodeMap.get(e.getParent()).add(node);
						nodeMap.put(e, node);
					}
				} else {
					if (nodeMap.containsKey(e)) {
						DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode(po2vo(e.getParent()));
						parentNode.add(nodeMap.get(e));
						nodeMap.put(e.getParent(), parentNode);
					} else {
						DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode(po2vo(e.getParent()));
						DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(po2vo(e));
						parentNode.add(childNode);
						nodeMap.put(e, childNode);
						nodeMap.put(e.getParent(), parentNode);
					}
				}
			} else {
				TEnterpriseRelation relation = null;
				for (TEnterpriseRelation r : e.getParentRelation()) {
					if (entities.contains(r.getParentEnterprise()) && r.getDepth() != 0) {
						if (BlankUtils.isBlank(relation) || relation.getDepth() > r.getDepth()) {
							relation = r;
						}
					}
				}

				if (BlankUtils.isBlank(relation)) {
					if (nodeMap.containsKey(e)) {
						rootNode.add(nodeMap.get(e));
					} else {
						DefaultMutableTreeNode node = new DefaultMutableTreeNode(po2vo(e));
						nodeMap.put(e, node);
						rootNode.add(node);
					}
				} else {
					if (nodeMap.containsKey(relation.getParentEnterprise())) {
						if (nodeMap.containsKey(e)) {
							nodeMap.get(relation.getParentEnterprise()).add(nodeMap.get(e));
						} else {
							DefaultMutableTreeNode node = new DefaultMutableTreeNode(po2vo(e));
							nodeMap.get(relation.getParentEnterprise()).add(node);
							nodeMap.put(e, node);
						}
					} else {
						if (nodeMap.containsKey(e)) {
							DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode(po2vo(relation.getParentEnterprise()));
							parentNode.add(nodeMap.get(e));
							nodeMap.put(relation.getParentEnterprise(), parentNode);
						} else {
							DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode(po2vo(relation.getParentEnterprise()));
							parentNode.add(new DefaultMutableTreeNode(po2vo(e)));
							nodeMap.put(relation.getParentEnterprise(), parentNode);
						}
					}
				}
			}
		}

		return new DefaultTreeModel(rootNode);
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param enterprise
	 *            企业值对象
	 * @return 返回企业实体对象
	 */
	public static TEnterprise vo2po(Enterprise enterprise) {

		TEnterprise tenterprise = new TEnterprise();

		BeanUtils.copyProperties(enterprise, tenterprise, new String[] { "status", "parent" });

		tenterprise.setStatus(Status.valueOf(enterprise.getStatus()));

		if (!BlankUtils.isBlank(enterprise.getParent()))
			tenterprise.setParent(new TEnterprise(enterprise.getParent().getId()));

		return tenterprise;
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param tenterprise
	 *            企业对象
	 * @return 返回企业值对象
	 */
	public static Enterprise po2vo(TEnterprise tenterprise) {

		Enterprise enterprise = new Enterprise();

		BeanUtils.copyProperties(tenterprise, enterprise, new String[] { "status", "parent" });

		enterprise.setStatus(Status.valueOf(tenterprise.getStatus()));

		return enterprise;
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param tentities
	 *            企业对象列表
	 * @return 返回企业值对象列表
	 */
	public static List<Enterprise> po2vo(List<TEnterprise> tentities) {
		List<Enterprise> entities = new ArrayList<Enterprise>();
		for (TEnterprise tenterprise : tentities) {
			entities.add(po2vo(tenterprise));
		}
		return entities;
	}
}
